<?php
namespace app\logic;

class CaiNiao
{
    private $secret_key = '05Qw3A7lhajhi9b3Wtdz432c3NIf77xF'; //测试：F53eqq903jQySV100Z8w06f9g914A13Z

    private $token = 'T3ZHVENJRVBHNHBvaHR0djAwVklwUG51cHN1NjVtRGJLbnQzWGlTdUFGSlBVOW9ydXJnZlMvdzRmZGlBZko4Vg=='; //测试：TmpFU1ZOUGoyRnoybDZmT3lyaW9hWGR4VFNad0xNYTBUek9QZk9kamt2Z1hJMytsVkVHK0FjVW55T25wcUR1Qw==

    private $url = 'http://link.cainiao.com/gateway/link.do'; //沙箱环境:https://linkdaily.tbsandbox.com/gateway/link.do

    private $company = [
        'ZJS' => 'http://cloudprint.cainiao.com/template/standard/901/110', //宅急送
        'YUNDA' => 'http://cloudprint.cainiao.com/template/standard/401/152', //韵达
        'GTO' => 'http://cloudprint.cainiao.com/template/standard/1101/98', //国通
        'DBKD' => 'http://cloudprint.cainiao.com/template/standard/1301/92', //德邦快递
        'EMS' => 'http://cloudprint.cainiao.com/template/standard/701/114', //EMS
        'QFKD' => 'http://cloudprint.cainiao.com/template/standard/1401/110', //全峰快递
        'UC' => 'http://cloudprint.cainiao.com/template/standard/1001/102', //优速
        'POSTB' => 'http://cloudprint.cainiao.com/template/standard/801/120', //邮政快递包裹
        'EYB' => 'http://cloudprint.cainiao.com/template/standard/1601/110', //EMS经济快递
        'STO' => 'http://cloudprint.cainiao.com/template/standard/201/160', //申通
        'SURE' => 'http://cloudprint.cainiao.com/template/standard/133204/5', //速尔
        'SF' => 'http://cloudprint.cainiao.com/template/standard/1501/62', //顺丰
        'ZTO' => 'http://cloudprint.cainiao.com/template/standard/301/176', //中通
        'YTO' => 'http://cloudprint.cainiao.com/template/standard/101/572', //圆通
        'TTKDEX' => 'http://cloudprint.cainiao.com/template/standard/601/136', //天天快递
        'HTKY' => 'http://cloudprint.cainiao.com/template/standard/501/130', //百世快递
        'FAST' => 'http://cloudprint.cainiao.com/template/standard/1201/98', //快捷快递
        'BESTQJT' => 'http://cloudprint.cainiao.com/template/standard/83910/69', //百世快运
        '5000000007756' => 'http://cloudprint.cainiao.com/template/standard/82710/15', //邮政标准快递
        '2608021499_235' => 'http://cloudprint.cainiao.com/template/standard/183119', //安能
        'CN7000001003751' => 'http://cloudprint.cainiao.com/template/standard/181603', //跨越
    ];

    public function getWaybill($cpCode)
    {
        $res = $this->getSubscription($cpCode); //订购关系不存在
        if (empty($res)) return -1;

        $msg_type = 'TMS_WAYBILL_GET';
        $data['cpCode'] = $cpCode;

        //发件人地址
        $data['sender'] = [
            'address' => [
                'province' => '福建省',
                'city' => '福州市',
                'district' => "鼓楼区",
                'town' => '津泰路',
                'detail' => '道山楼'
            ],
            'phone' => '15394401837',
            'mobile' => '15394401837',
            'name' => '杰哥哥',
        ];
        //物流服务
        $data['tradeOrderInfoDtos'][0]['logisticsServices'] = '';
        $data['tradeOrderInfoDtos'][0]['objectId'] = 1;

        //订单信息
        $data['tradeOrderInfoDtos'][0]['orderInfo'] = [
            'orderChannelsType' => 'OTHERS',
            'tradeOrderList' => ['2018030411'], //订单号
        ];

        //包裹信息
        $data['tradeOrderInfoDtos'][0]['packageInfo'] = [
            'volume' => '',
            'weight' => '',
            'id' => '',
            'items' => [
                ['count' => '1', 'name' => '衣服'],
            ],
        ];

        //收件人地址
        $data['tradeOrderInfoDtos'][0]['recipient'] = [
            'address' => [
                'province' => '福建省',
                'city' => '福州市',
                'district' => "鼓楼区",
                'town' => '津泰路',
                'detail' => '道山楼'
            ],
            'phone' => '15394401837',
            'mobile' => '15394401837',
            'name' => '杰哥哥',
        ];

        $data['tradeOrderInfoDtos'][0]['templateUrl'] = $this->company[$cpCode];
        $data['tradeOrderInfoDtos'][0]['userId'] = 1;
        echo $this->common($msg_type, json_encode($data));
        die;
    }


    public function aa()
    {
        echo json_encode($this->getSubscription(''));
    }

    /**
     * 获取订购关系
     * @param $cpCode string 物流公司简码
     * @return array
     */
    public function getSubscription($cpCode = '')
    {
        $msg_type = 'TMS_WAYBILL_SUBSCRIPTION_QUERY';
        $data['cpCode'] = $cpCode;
        $res = json_decode($this->common($msg_type, json_encode($data)), true);
        if ($res['success'] == 'true') return $res['waybillApplySubscriptionCols'];
        return [];
    }

    /**
     * 公共函数
     * @param string $msg_type
     * @param string $logistics_interface
     * @return string
     */
    public function common($msg_type = '', $logistics_interface = '')
    {
        $data = [
            'msg_type' => $msg_type,
            'logistic_provider_id' => $this->_getToken(),
            'data_digest' => $this->_getSign($logistics_interface),
            'to_code' => '',
            'logistics_interface' => $logistics_interface,
        ];
        return $this->_curlPost($this->url, http_build_query($data));
    }

    /**
     * 签名
     * @param $content
     * @return string
     */
    private function _getSign($content)
    {
        return base64_encode(md5($content . $this->_getSecretKey(), 'utf-8'));
    }

    /**
     * 获取token
     * @return string
     */
    private function _getToken()
    {
        return $this->token; //return 'TmpFU1ZOUGoyRnoybDZmT3lyaW9hWGR4VFNad0xNYTBUek9QZk9kamt2Z1hJMytsVkVHK0FjVW55T25wcUR1Qw=='; //测试

    }

    /**
     * 获取secretKey
     * @return string
     */
    private function _getSecretKey()
    {
        return $this->secret_key; //return 'F53eqq903jQySV100Z8w06f9g914A13Z'; //测试

    }

    /**
     * 模拟表单提交
     * @access protected
     * @param string $url 链接
     * @param array|string $data 数据
     * @since 1.0
     * @return string
     */
    private function _curlPost($url, $data, $header = ["Content-Type: application/x-www-form-urlencoded"])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $info = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Errno' . curl_error($ch);
        }
        curl_close($ch);
        return $info;
    }
}
